program parallel_sum
    use omp_lib
    implicit none
    integer, parameter :: N = 10000000 ! 1000万个元素
    integer :: i
    integer :: count_start, count_end, count_rate ! <--- 新增
    ! 使用双精度浮点数
! 原始：real(kind=8) :: sum_val, serial_sum, x(N)
! 改变为：
    real(kind=8), ALLOCATABLE :: x(:)
    real(kind=8) :: sum_val, serial_sum
    real :: start_time, end_time ! <--- 新增 

    ! 1. 初始化数组，并计算串行结果作为参考
    ALLOCATE(x(N))
    sum_val = 0.0d0
    serial_sum = 0.0d0
    call system_clock(count=count_start, count_rate=count_rate) ! <--- 计时开始
    do i = 1, N
        x(i) = i * 1.0d0 
        serial_sum = serial_sum + x(i) 
    end do
    call system_clock(count=count_end)   ! <--- 计时结束
    print *, "Serial Sum (Reference): ", serial_sum
    print *, "Serial Time (seconds): ", real(count_end - count_start, kind=8) / count_rate ! <--- 打印时间
!    DEALLOCATE(x)

    sum_val = 0.0d0
!    ALLOCATE(x(N))
    call system_clock(count=count_start, count_rate=count_rate) ! <--- 计时开始
    ! 2. OpenMP 并行计算开始
    !$OMP PARALLEL DO PRIVATE(i) REDUCTION(+:sum_val)
    ! REDUCTION(+:sum_val) 指定 sum_val 变量为归约变量，确保每个线程的部分和最终正确合并。
    do i = 1, N
        sum_val = sum_val + x(i)
    end do
    !$OMP END PARALLEL DO
    call system_clock(count=count_end)   ! <--- 计时结束
    print *, "Parallel Sum (Result): ", sum_val
    print *, "Parallel Time (seconds): ", real(count_end - count_start, kind=8) / count_rate ! <--- 打印时间
    DEALLOCATE(x)
end program parallel_sum